package leetCode.firstWeek;

import java.util.ArrayList;
import java.util.List;

public class Code_4 {
  public double findMedianSortedArrays(int[] nums1, int[] nums2) {
    List<Integer> totalNum = new ArrayList<>();
    int p1 = 0, p2 = 0;
    int totalLength = nums1.length + nums2.length;
    for (int i = 0; i < totalLength; i++) {
      if (p2 != nums2.length && p1 != nums1.length) {
        if (nums1[p1] > nums2[p2]) {
          totalNum.add(nums2[p2]);
          p2++;
        } else {
          totalNum.add(nums1[p1]);
          p1++;
        }
      } else {
        if (p1 == nums1.length) {
          totalNum.add(nums2[p2]);
          p2++;
        } else {
          totalNum.add(nums1[p1]);
          p1++;
        }
      }
    }

    return totalLength % 2 == 1
        ? totalNum.get((totalLength + 1) / 2 - 1).doubleValue()
        : (totalNum.get(totalLength / 2 - 1).doubleValue()
                + totalNum.get(totalLength / 2).doubleValue())
            / 2;
  }
}
